package com.geostar.constructionland.analyse.agri;

import com.geostar.constructionland.common.entity.response.LandInfo;
import org.apache.commons.collections4.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author yelll
 * @since 2020-6-4 11:55
 **/
public class AdjustAgri {
    /***
     *
     * @param landInfos 地块信息
     * @param adjustTotal 平差总值
     * @param adjustUnit 平差单位
     * @return
     * @throws Exception
     */
    public static List<LandInfo> adjust(List<LandInfo> landInfos, Double adjustTotal, Double adjustUnit) throws Exception {
        if (CollectionUtils.isEmpty(landInfos)) {
            return null;
        }
        /**设置占压后的默认面积*/
        landInfos.stream().forEach(landInfo -> {
            if (landInfo.getZymj_adjusted() == 0) {
                landInfo.setZymj_adjusted(new BigDecimal(landInfo.getZymj_ys()).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue());
            }
        });
        /**确定需要平差的次数**/
        long adjustTimes = new BigDecimal(Math.abs(adjustTotal / adjustUnit))
                .setScale(0, BigDecimal.ROUND_UP).longValue();

        /***设置最大平差值，超过最大平差值 则 抛出异常*/
        long maxCircleTime = adjustTimes * 100;
        if (adjustTotal > 0) {
            adjustUnit = adjustUnit * -1;
        }
        long circleTime = 0;
        while (adjustTimes > 0) {
            for (LandInfo landInfo : landInfos) {
                if (adjustTimes <= 0) {
                    break;
                }
                circleTime++;
                double zymj_adjusted = landInfo.getZymj_adjusted();
                zymj_adjusted = zymj_adjusted + adjustUnit;
                if (zymj_adjusted >= 0) {
                    /**平差过后面积大于0,下面继续平差**/
                    landInfo.setZymj_adjusted(new BigDecimal(zymj_adjusted).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue());
                    adjustTimes--;
                } else {
                    continue;
                }
            }
            if (circleTime > maxCircleTime) {
                throw new Exception("程序遇到问题咯!");
            }
        }
        return landInfos;
    }
}
